<template>
  <div class="background-container">
    <video ref="videoPlayer" :key="currentVideo" preload="atuo" toplay muted loop playsinline auto>
      <source :src="currentVideo" type="video/mp4">
      </source>
    </video>
    <!-- <audio autoplay>
      <source src="/music/night.mp3" type="audio/mp3">
    </audio> -->
  </div>
</template>


<script lang="ts">
import { gsap } from 'gsap'
export default defineComponent({
  async setup() {

    const data = reactive({
      BackgroundVideoUrl: [
        {url: "https://resource-cdn.obsbothk.com/video/sea.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/medium.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/168787-839864519.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/188057-881538748.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/188861-883827797.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/cloud.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/161045-822582085_large.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/202982-919365848_large.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/188021-881528788_large.mp4"},
        {url: "https://resource-cdn.obsbothk.com/video/175876-854230219_large.mp4"}
      ],
      currentVideoIndex: ref(),
      currentVideo: ref("https://resource-cdn.obsbothk.com/video/188057-881538748.mp4"),
      videoPlayer: ref(),
    })


    const changVideo = async() => {
      data.currentVideoIndex = 0
      function changeVideoSource() {
        data.currentVideoIndex = (data.currentVideoIndex + 1) % data.BackgroundVideoUrl.length;
        data.currentVideo = data.BackgroundVideoUrl[data.currentVideoIndex].url
        nextTick(() => {
          loadAndPlayVideo(data.videoPlayer);
        });
      }
      nextTick(() => {
        loadAndPlayVideo(data.videoPlayer);
      });

      setInterval(changeVideoSource, 10000);
    }


    const loadAndPlayVideo = async(video: any) => {
      if (!video) {
        console.error("Provided video element is not valid");
        return;
      }
      video.load();
      video.currentTime = 0;
      video.play().catch((e: any) => {
        console.error('Error playing video:', e);
      });
      video.addEventListener('error', (event: any) => {
        console.error('Error loading video:', video.error);
      });
    }



    onMounted(() => {
      changVideo()
    })



    return {
      ...toRefs(data),
      changVideo
    }

  }
})
</script>




